﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using Telerik.Windows.Controls;
using TruckScale.Models;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    private string _dateFliter = "Day";
    private string _weighStatus = "0";
    private DateTime? _startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
    private DateTime? _endTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
    //private int _sortBy = 0;
    public DataTable RecordDT { get; private set; } //经过转换的称重记录表格，用来显示到列表、导出到excel
    public DataRow SelectedRecrod { get; set; } //选中的称重记录
    public DelegateCommand DoubleClickCommand { get; set; }
    public string DateFliter
    {
      get => _dateFliter;
      set
      {
        _dateFliter = value;
        if (value == "Day")
        {
          StartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
          EndTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
        }
        else if (value == "Month")
        {
          StartTime = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
          EndTime = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
        }
      }
    }
    public string WeighStatus
    {
      get => _weighStatus;
      set
      {
        _weighStatus = value;
        //查询逻辑
        QueryRecordList();
      }
    }
    //public int SortBy
    //{
    //  get => _sortBy;
    //  set
    //  {
    //    _sortBy = value;
    //    //查询逻辑
    //    QueryRecordList();
    //  }
    //}
    public DateTime? StartTime
    {
      get => _startTime;
      set
      {
        _startTime = value;
        //查询逻辑
        QueryRecordList();
      }
    }
    public DateTime? EndTime
    {
      get => _endTime;
      set
      {
        _endTime = value;
        //查询逻辑
        QueryRecordList();
      }
    }
    public int Counts { get; set; }
    public decimal TotalMz { get; set; }
    public decimal TotalJz { get; set; }

    private void InitWeighRecordProps()
    {
      QueryRecordList();
    }

    private void InitWeighRecordCommands()
    {
      DoubleClickCommand = new DelegateCommand(OnDoubleClickCommandExcuted);
    }

    private void OnDoubleClickCommandExcuted(object obj)
    {
      if (SelectedRecrod == null)
      {
        return;
      }
      foreach (var item in SelectedRecrod.ItemArray)
      {
        if (Regex.IsMatch(item.ToString(), "\\d{12}$"))
        {
          WeighRecord = WeighRecordModel.SelectRecordByBh(item.ToString());

          //不把已完成的称重记录显示到表单里
          if (WeighRecord.IsFinish)
          {
            WeighRecord = new WeighRecordModel();
          }

          InitWeighFormProps();
          CheckBtnEnable();
          break;
        }
      }
    }

    private void QueryRecordList()
    {
      if (StartTime == null || EndTime == null || WeighStatus == null)
      {
        return;
      }

      //查不到数据说明数据库连接失败，直接返回
      if (WeighFormField == null)
      {
        return;
      }

      //根据显示在界面上的字段构造称重记录表格
      var dt = new DataTable("WeighingRecord");
      foreach (var f in WeighFormField)
      {
        dt.Columns.Add(f.WeighFormValue);
      }

      //查询数据库中的称重记录
      string startTime = ((DateTime)StartTime).ToString("yyyy-MM-dd HH:mm:ss");
      string endTime = ((DateTime)EndTime).ToString("yyyy-MM-dd HH:mm:ss");
      //string sortField = "auto_no";
      //if (SortBy == 0) sortField = "bh";
      //if (SortBy == 1) sortField = "mzsj";
      //if (SortBy == 2) sortField = "pzsj";

      List<WeighRecordModel> wrList = null;
      if (WeighStatus != "1")
      {
        wrList = WeighRecordModel.SelectUnFinishRecord(startTime, endTime);
      }
      if (WeighStatus != "0")
      {
        wrList = (wrList == null) ? WeighRecordModel.SelectFinishRecord(startTime, endTime) :
          wrList.Concat(WeighRecordModel.SelectFinishRecord(startTime, endTime)).ToList();
      }
      var goodList = GoodsModel.SelectValidGoods();
      var customerList = CustomerModel.SelectValidCustomer();
      var userList = UserModel.SelectValidUser();

      //将称重记录放入dt，显示到界面
      foreach (var wr in wrList)
      {
        DataRow row = dt.NewRow();

        foreach (var f in WeighFormField)
        {
          string key = Regex.Replace(f.WeighFormKey.Substring(1), "^[a-z]", m => m.Value.ToUpper());

          row[f.WeighFormValue] = wr.GetType().GetProperty(key).GetValue(wr);

          if (key == "Wz" && row[f.WeighFormValue] != DBNull.Value)
          {
            row[f.WeighFormValue] = goodList.Find(g => g.GoodsId == Convert.ToInt32(row[f.WeighFormValue]))?.GoodsName;
          }
          if (key.StartsWith("Kh") && row[f.WeighFormValue] != DBNull.Value)
          {
            //var rst = row[f.WeighFormValue];
            row[f.WeighFormValue] = customerList.Find(c => c.CustomerId == Convert.ToInt32(row[f.WeighFormValue]))?.CustomerName;
          }
          if (key.EndsWith("sby") && row[f.WeighFormValue] != DBNull.Value)
          {
            row[f.WeighFormValue] = userList.Find(u => u.UserId == Convert.ToInt32(row[f.WeighFormValue]))?.UserName;
          }
        }

        dt.Rows.Add(row);
      }

      RecordDT = dt;

      var wrCount = WeighRecordModel.SelectCount(startTime, endTime);
      Counts = wrCount.WeighCount;
      TotalMz = wrCount.TotalMz;
      TotalJz = wrCount.TotalJz;
    }
  }
}

